//
//  YRPlaySlider.swift
//  TestPlaySlider
//
//  Created by 薛永伟 on 2019/9/25.
//  Copyright © 2019 XueYongWei. All rights reserved.
//

import UIKit

class YRDisplayValueSlider: UISlider {

    /// 值的字体
    var valueTextFont:UIFont = UIFont.systemFont(ofSize: 15, weight: .regular){
        
        didSet{
            valueLabel.font = valueTextFont
        }
    }
    
    /// 值的颜色
    var valueTextColor = UIColor.black {
        
        didSet{
            valueLabel.textColor = valueTextColor
        }
    }
    
    fileprivate lazy var valueLabel: UILabel = {
        
        let view = UILabel()
        view.text = ""
        view.textColor = UIColor.black
        view.font = UIFont.systemFont(ofSize: 15, weight: .regular)
        view.textAlignment = .center
        return view
    }()
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        
        super.init(coder: aDecoder)
        setup()
    }
    
    func setup(){
        
        valueLabel.frame = CGRect.init(origin: CGPoint.zero, size: thumbSize)
        addSubview(valueLabel)
    }

    
    fileprivate var thumbRect: CGRect {
        
        let trackRect = self.trackRect(forBounds: self.bounds)
        let thumbRect = self.thumbRect(forBounds: self.bounds, trackRect: trackRect, value: self.value)
        return thumbRect
    }
    
    fileprivate var thumbSize:CGSize {
        
        return thumbRect.size
    }
    
    fileprivate func updateVauleLabel(){
        
        let valueString = String.init(format: "%.1f", self.value)
        valueLabel.text = valueString
    }
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        let rect = thumbRect
        let center = CGPoint.init(x: rect.midX, y: rect.midY)
        
        valueLabel.center = center
        updateVauleLabel()
        
        bringSubviewToFront(valueLabel)
    }
    
}
